package com.java.hohenheim.springplatform.redis.ops;


import com.java.hohenheim.springplatform.db.entity.AccountEntity;
import io.lettuce.core.RedisException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class AccountRedisOps {
    private final String KEY_SUFFIX = "account:user:info:";

    private final int TIME_OUT_MINUTES = 20; //注册验证码超时时间，20分钟

    @Resource(name = "RegisterUserInfoRedis")
    private RedisTemplate<String, AccountEntity> mRegisterUserInfoRedis;

    /**
     * 存储用户信息
     *
     * @param userId        用户ID
     * @param accountEntity 用户对象
     * @return true：保存成功；false：保存失败
     */
    public boolean saveUserInfo(long userId, AccountEntity accountEntity) {
        String key = KEY_SUFFIX + userId;
        try {
            mRegisterUserInfoRedis.opsForValue().set(key, accountEntity);
        }
        catch (RedisException e) {
            log.error("用户" + userId + "信息缓存失败", e);
            return false;
        }
        return true;
    }


    /**
     * 获取用户信息
     *
     * @param userId 用户名稱
     * @return 用户对象
     */
    public AccountEntity getAccountInfo(long userId) {
        ValueOperations<String, AccountEntity> redisOps = mRegisterUserInfoRedis.opsForValue();
        AccountEntity accountEntity = null;
        try {
            accountEntity = redisOps.get(KEY_SUFFIX + userId);
        }
        catch (NullPointerException e) {
            return null;
        }
        return accountEntity;
    }

    /**
     * 判断是否存在KEY
     *
     * @param userId 用户名稱
     * @return true：存在；false：不存在
     */
    public boolean isUserInfo(long userId) {
        String key = KEY_SUFFIX + userId;
        try {
            Boolean has = mRegisterUserInfoRedis.hasKey(key);
            return null==has ? false : has;
        }
        catch (NullPointerException e) {
            log.error("用户" + userId + "缓存不存在", e);
            return false;
        }
    }
}
